package com.dataart.training.crimequalification.facesutils;


import javax.faces.context.FacesContext;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class ResourceBundleManager {

    /**
     * Returns resource bundle looked up by its name.
     *
     * @param name name of the desired bundle, must not be empty
     * @return resource bundle by given name if such exists
     */
    public ResourceBundle getResourceBundleByName(String name) {

        if (name.isEmpty()) {
            throw new IllegalArgumentException("Name of the resource bundle must be specified.");
        }

        FacesContext context = FacesContext.getCurrentInstance();
        ResourceBundle resourceBundle = context.getApplication().getResourceBundle(context, name);

        if (resourceBundle == null) {
            throw new MissingResourceException("No such resource bundle registered. ", ResourceBundle.class.getName(), name);
        }

        return resourceBundle;

    }

    /**
     * Returns value from a resource bundle by specified key.
     *
     * @param bundle resource bundle to look up value in
     * @param key    lookup key, must not be empty
     * @return value assigned to key from bundle
     */
    public String getValueFromBundleByKey(ResourceBundle bundle, String key) throws MissingResourceException {

        if (key.isEmpty()) {
            throw new IllegalArgumentException("Key to look up value by in the resource must be specified.");
        }

        return bundle.getString(key);
    }

}
